# -*- coding: utf-8 -*-
import copy

from zc_core.dao.item_data_dao import ItemDataDao
from zc_core.dao.sku_dao import SkuDao
from zc_core.spiders.base import BaseSpider
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.http_util import retry_request
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.done_filter import DoneFilter

from nbgh.rules import *


class FullSpider(BaseSpider):
    name = "full"
    # 详情页url
    item_url = "https://mp.nbgh.gov.cn/wechatPage/api/api2/prod/{}"

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no, query={'stock': {'$exists': True}})

    def start_requests(self):
        sku_list = ItemDataDao().get_batch_data_list(self.batch_no)
        self.logger.info('全量: %s' % (len(sku_list)))
        for sku in sku_list:
            sku_id = sku.get('_id')
            settings = get_project_settings()
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: %s', sku_id)
                continue

            yield Request(
                url=self.item_url.format(sku_id),
                meta={
                    'reqType': 'full',
                    'batchNo': self.batch_no,
                    "skuId": sku_id,
                },
                # headers={
                # },
                callback=self.parse_item_data,
                errback=self.error_back
            )

    def parse_item_data(self, response):
        meta = response.meta
        sku_id = meta.get("skuId")
        item = parse_item_data(response)
        item['batchNo'] = self.batch_no
        self.logger.info('商品: sku=%s' % sku_id)
        yield item
